var util = require('../../utils/util.js');
var app = getApp();
var md5 = require("../../utils/md5.js");
const Upyun = require('../../utils/upyun-wxapp-sdk');
var phone = '';
const upyun = new Upyun({
  bucket: 'artartimages',
  operator: 'upyunadmin2014',
  getSignatureUrl: 'https://api.artart.cn/api.php?ac=signupyun&publickey=' + util.publiccode
})
Page({
  data: {
      minHeight: 0,
      userInfo:{},
      sex:["请选择性别","男","女"],
      careerDirectionOne:[],
      careerDirectionTwo:[],
      careerDirectionThree: [],
      careerDirectionOneIndex:0,
      careerDirectionTwoIndex:0,
      careerDirectionThreeIndex: 0,
      careerDirectionOneId: [],
      careerDirectionTwoId: [],
      careerDirectionThreeId: [],
      uploadImg:[],
      pickerViewDisplay:"none",
      tx:"",
      isnew:0,
      sendCodeOK: false
  },
  loadMore:function(){
      if(!noMore){
        page ++;
        this.load();
      }
  },
  onLoad: function(data){
    var that = this;
    var uid = data.uid;
    var isnew = data.new;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 5000
    })
    app.GetUserInfo(uid, function(res){
      phone = res.phone;
      //更新数据
      console.log("new card userInfo:", res);
      that.setData({
        userInfo:res,
        uploadImg:res.photo.split(','),
        isnew: isnew,
        csel: res.usercata.split(','),
        cselid: res.usercataxcx.split(',')
      }) 
      
      // usercata:"手工匠人"
      // usercataxcx:"96"
      if (res.usercata && parseInt(res.usercataxcx) > 0) {
        wx.hideToast();
        app.dialogToast('已建名片', 'success', function () { wx.reLaunch({
            url: '/pages/index/index',
          })
        });
      } else {
        that.loadUserCata();
        that.load();
        wx.hideToast();
      }
    });
    
  },
  loadUserCata:function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "usercata"
      },
      success: function (responseData) {
        var resData = [];
        var resId = [];
        for (var i = 0; i < responseData.data.length; i++) {
          resData = resData.concat([responseData.data[i].title]);
          resId = resId.concat([responseData.data[i].user_category_id]);
        }
        that.setData({
          careerDirectionOne: ["第一身份"].concat(resData),
          careerDirectionTwo: ["第二身份"].concat(resData),
          careerDirectionThree: ["第三身份"].concat(resData),
          careerDirectionOneId: [0].concat(resId),
          careerDirectionTwoId: [0].concat(resId),
          careerDirectionThreeId: [0].concat(resId),
        });
      }
    });
  },

  load:function(){
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          minHeight:res.windowHeight-45,
          imgWH:(res.windowWidth-18)/4-12
        });
      }
    });
  },
  bindPickerChange: function(e){
    var name = e.currentTarget.dataset.name;
    if(name == "cd"){
      this.setData({
        careerDirectionIndex: e.detail.value
      })
    }else if(name == "one"){
      this.setData({
        csel:[],
        careerDirectionOneIndex: e.detail.value
      })
    }else if(name == "two"){
      this.setData({
        careerDirectionTwoIndex: e.detail.value
      })
    }else if(name == "three"){
      this.setData({
        careerDirectionThreeIndex: e.detail.value
      })
    }
  },
  saveCard: function(e){
    var that = this;
    console.log("formId: ", e.detail.formId);
    app.saveFormId(e.detail.formId);

    var tmpmd5 = md5.hexMD5(app.globalData.userInfo.uid + "usercominfo" + app.globalData.userInfo.token);
    if (!e.detail.value.name || !e.detail.value.moble || !e.detail.value.one || !e.detail.value.qm || !e.detail.value.wx || !e.detail.value.email) {
      wx.showToast({
        title: '请完整填写资料',
        icon: 'loading',
        duration: 1000
      })
    } else if (!e.detail.value.yzm) {
      wx.showToast({
        title: '请填写验证码',
        icon: 'loading',
        duration: 1000
      })
    } else {

      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      wx.showToast({
        title: '资料保存中',
        icon: 'loading',
        duration: 2000
      })
      util.api({
        data: {
          "publickey": util.publiccode,
          "phone": phone,
          "code": e.detail.value.yzm,
          "ac": 'checksmsmob'
        },
        success: function (responseData) {
          //console.log(responseData.data.res);
          if (!responseData.data.res) {
            console.log(responseData.data)
            wx.showToast({
              title: '验证码有误',
              icon: 'loading',
              duration: 1000
            })
          } else {

            util.api({
              data: {
                "privatekey": tmpmd5,
                "ac": "usercominfo",
                "uid": app.globalData.userInfo.uid,
                "realname": e.detail.value.name,
                "phone": e.detail.value.moble,
                "avatar": e.detail.value.txval,
                "usercata": e.detail.value.one + (e.detail.value.two ? ',' + e.detail.value.two : '') + (e.detail.value.three ? ',' + e.detail.value.three : ''),
                "myword": e.detail.value.qm,
                "weixin": e.detail.value.wx,
                "email": e.detail.value.email,
                "photos": that.data.uploadImg.map(function (item) { return item.replace('wxfile://tmp_', 'http://img.artart.cn/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(','),
                "intro": e.detail.value.desc ? e.detail.value.desc : 0
              },
              method: "POST",
              success: function (responseData) {
                console.log("new card: ", responseData);
                if (responseData.statusCode == 200 && responseData.data) {
                  if(responseData.data.res != undefined && !responseData.data.res) {
                    app.dialog(responseData.data.msg, 'loading');
                  } else {
                    wx.clearStorageSync();
                    app.dialog('新建名片成功', 'success', function () { wx.redirectTo({ url: '/pages/share-poster/share-poster' }) });
                  }
                } else {
                  app.dialog('新建名片失败', 'loading');
                }
              }
     
     
            });
   
          }
        }
      });
    }
    
  },
  bindChange: function(e){
    var val = e.detail.value;
    var newVal = val;
    // console.log(val, citysValue);
   
    
  },
  showPickerView: function(){
    this.setData({
      pickerViewDisplay:"block"
    });
  },
  hidePickerView: function(){
    this.setData({
      pickerViewDisplay:"none"
    });
  },
  changePhone: function(event) {
    phone = event.detail.value;
  },
  sendCode: function() {
    var that = this;
    if (this.data.sendCodeOK){
      // wx.showToast({
      //   title: '验证码已发送',
      // })
      return;
    }
    util.api({
      data: {
        "publickey": util.publiccode,
        "phone": phone,
        "ac": "sendsmsmob"
      },
      success: function (responseData) {
        console.log(responseData.data.res);
        if (responseData.data.res == true) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 1000
          })
        } else {
          wx.showToast({
            title: '手机号有误',
            icon: 'success',
            duration: 1000
          })
        }
        that.setData({
          sendCodeOK: true
        });
      }
    });
  },
  uploadImg: function(){
    var that = this;
    var photos = this.data.uploadImg;
    wx.chooseImage({
      count: 9, 
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        for (var photoi = 0; photoi < tempFilePaths.length; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda)+'/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {

              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 1000
              })

              that.setData({
                uploadImg: tempFilePaths.concat(photos)
              })
            },
            fail: function ({errMsg}) {
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
      },
      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }
      // success: function (res) {
      //   var tempFilePaths = res.tempFilePaths;
      //   that.setData({
      //     uploadImg: tempFilePaths.concat(photos)
      //   });
      //   console.log(that.uploadImg);
      // }
    });
  },
  uploadTX: function () {
    var that = this;
    wx.chooseImage({
      count: 1,

      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {

        const imageSrc = res.tempFilePaths[0]
        const avatarUrl = '/avatar/xcx/' + imageSrc.split('_')[1]
        upyun.upload({
          localPath: imageSrc,
          remotePath: avatarUrl,
          success: function (res) {

            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })

            that.setData({
              tx: 'http://img.artart.cn' + avatarUrl
            })
          },
          fail: function ({errMsg}) {
            console.log('uploadImage fail, errMsg is', errMsg)
          }
        })
      },
      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }

      
    });
  }
})